import logging
import logging.handlers
# from msilib.schema import Error
import os
import time


class logMsg(logging.Logger):
    def __init__(self, log_level='DEBUG'):
        super().__init__("")
        # 设置输出的等级
        LEVELS = {
            'NOSET': logging.NOTSET,
            'DEBUG': logging.DEBUG,
            'INFO': logging.INFO,
            'WARNING': logging.WARNING,
            'ERROR': logging.ERROR,
            'CRITICAL': logging.CRITICAL
        }
        # 确保传入的日志等级是有效的
        log_level = LEVELS.get(log_level.upper(), logging.DEBUG)
        # 创建文件目录
        logs_dir = "logs_msg"
        if os.path.exists(logs_dir) and os.path.isdir(logs_dir):
            pass
        else:
            os.mkdir(logs_dir)
        # 修改log保存位置
        timestamp = time.strftime("%Y-%m-%d", time.localtime())
        logfilename = '%s.log' % timestamp
        logfilepath = os.path.join(logs_dir, logfilename)
        rotatingFileHandler = logging.handlers.RotatingFileHandler(
            filename=logfilepath, maxBytes=1024 * 1024 * 50, backupCount=5)
        rotatingFileHandler.setLevel(log_level)
        # 设置输出格式
        formatter = logging.Formatter(
            '[%(asctime)s] [%(levelname)s] %(filename)s:%(lineno)d %(message)s',
            '%Y-%m-%d %H:%M:%S')
        rotatingFileHandler.setFormatter(formatter)
        # 控制台句柄
        console = logging.StreamHandler()
        console.setLevel(logging.NOTSET)
        console.setFormatter(formatter)
        # 添加内容到日志句柄中
        self.addHandler(rotatingFileHandler)
        self.addHandler(console)
        self.setLevel(logging.NOTSET)

    @staticmethod
    def clean_msg():
        logs_dir = "logs_msg"
        current = int(time.time()) - 3600 * 72
        if os.path.exists(logs_dir) and os.path.isdir(logs_dir):
            for root, ds, fs in os.walk(logs_dir):
                for f in fs:
                    if '.log' in f:
                        try:
                            temp_time = f.split('.')[0]
                            timeArray = time.strptime(temp_time, "%Y-%m-%d")
                            timeStamp = int(time.mktime(timeArray))
                            if timeStamp < current:
                                logfilepath = os.path.join(logs_dir, f)
                                logMsg().info("delete: " + logfilepath)
                                if os.path.exists(logfilepath):
                                    os.remove(logfilepath)
                        except:
                            logMsg().info("delete logs have error: " + str(f))

    @staticmethod
    def try_except_error(msg=""):
        import traceback
        trace_info = traceback.format_exc()
        logMsg().error(str(msg) + "-----" + str(trace_info))

logMsgs = logMsg(log_level='DEBUG')
